/**
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */
import { YearViewItem } from '../types/year';
import { DateObject } from '../types/common';
import { useDate } from './use-date';
import { useMonth } from './use-month';
import useDisableMonth from './use-disable-month';
import { UseYear } from './types';

export function useYear(): UseYear {

    const { getToday } = useDate();
    const { daysInMonth } = useMonth();
    const { isMonthDisabledByDisableSince, isMonthDisabledByDisableUntil } = useDisableMonth();

    function generateYears(
        input: number,
        selectedMonth: DateObject,
        min: number,
        max: number,
        disableSince: DateObject,
        disableUntil: DateObject
    ): YearViewItem[][] {

        const years: YearViewItem[][] = [];
        const beginningYearInDecenniad: number = input - (input % 10);

        const { year: selectedYear, month } = selectedMonth;

        const today: DateObject = getToday();

        const capacityPerRow = 3;
        const nextDecenniad = beginningYearInDecenniad + 10;

        for (let startYearInRow = beginningYearInDecenniad - 1; startYearInRow < nextDecenniad; startYearInRow += capacityPerRow) {
            const yearsInRow: YearViewItem[] = [];
            for (let year = startYearInRow; year < startYearInRow + capacityPerRow; year++) {
                const disabled: boolean = isMonthDisabledByDisableSince({ year, month, day: 1 }, disableSince) ||
                    isMonthDisabledByDisableUntil({ year, month, day: daysInMonth(month || 0, year) }, disableUntil);

                const isOverstepped: boolean = year < min || year > max;
                yearsInRow.push({
                    year,
                    isCurrent: year === today.year,
                    selected: year === selectedYear,
                    disable: disabled || isOverstepped,
                    date: { year }
                });
            }
            years.push(yearsInRow);
        }

        return years;
    }

    return { generateYears };
}
